package class41To50;

public class LargestOneBorderedSquare {
    public int largest1BorderedSquare(int[][] grid) {
        int n = grid.length;
        int m = grid[0].length;
        build(grid);
        if (sum(grid, 0, 0, n - 1, m - 1) == 0) return 0;
        int ans = 1;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                for (int c = i + ans, d = j + ans, k = ans + 1; c < n && d < m; c++, d++, k++) {
                    if (sum(grid, i, j, c, d) - sum(grid, i + 1, j + 1, c - 1, d - 1) == (k - 1) * 4) {
                        ans = k;
                    }
                }
            }
        }

        return ans * ans;
    }

    private int sum(int[][] grid, int a, int b, int c, int d) {
        return a > c ? 0 : getVal(grid, c, d) - getVal(grid, c, b - 1) - getVal(grid, a - 1, d) + getVal(grid, a - 1, b - 1);
    }

    private void build(int[][] grid) {
        int n = grid.length;
        int m = grid[0].length;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                grid[i][j] += getVal(grid, i - 1, j) + getVal(grid, i, j - 1) - getVal(grid, i - 1, j - 1);
            }
        }
    }

    private int getVal(int[][] grid, int i, int j) {
        return (i < 0 || j < 0) ? 0 : grid[i][j];
    }
}
